/**
 * Author:yuiop
 * Date:2022/8/2 09:04
 */
package com.devops.graphql.handler;

import com.devops.common.exception.HandleDataException;
import com.devops.common.exception.SimilarNameException;
import graphql.execution.DataFetcherExceptionHandler;
import graphql.execution.DataFetcherExceptionHandlerParameters;
import graphql.execution.DataFetcherExceptionHandlerResult;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Component
public class CustomDataFetchingExceptionHandler implements DataFetcherExceptionHandler {

    @Override
    public CompletableFuture<DataFetcherExceptionHandlerResult> handleException(DataFetcherExceptionHandlerParameters handlerParameters) {
        Throwable throwable = handlerParameters.getException();
        CustomGraphQLError error;
        if (throwable instanceof UnauthenticatedException) {
            error = new CustomGraphQLError("该用户未认证", "401");
        } else if (throwable instanceof UnauthorizedException) {
            error = new CustomGraphQLError("该用户未授权", "403");
        } else if (throwable instanceof SimilarNameException) {
            error = new CustomGraphQLError(throwable.getMessage() + "#599", "599");
        } else if (throwable instanceof HandleDataException) {
            error = new CustomGraphQLError(throwable.getMessage() + "#598", "598");
        } else {
            error = new CustomGraphQLError(throwable.getMessage(), "500");
        }
        DataFetcherExceptionHandlerResult result = DataFetcherExceptionHandlerResult.newResult()
                .error(error)
                .build();
        return CompletableFuture.completedFuture(result);
    }
}
